import xmind
import time
import os
import requests
import random
from flask import current_app, g
from apps.project.business.zentao import ZenTaoBusiness
from functools import lru_cache

# from apps.project.middle.xmind import XmindData
# from apps.project.models.xmind import Xmind
# from library.api.db import db
# from apps.project.business.excel import ExcelBusiness
# from apps.project.business.zentao import ZenTaoBusiness
# from apps.interface.business.interfaceapimsg import InterfaceApiMsgBusiness
from apps.project.middle.zt_case import CaseData
# from apps.project.middle.zentao import Zentao
from apps.auth.extentions import parse_pwd
from flask import current_app, g
from library.trpc import Trpc
from multiprocessing import Process


class Xmind(object):
    user_trpc = Trpc('auth')
    public_trpc = Trpc('public')
    
    def __init__(self, import_type, path):
        """
        :param import_type: 导入类型
        :param path: 文件路径
        """
        self.import_type = import_type
        self.path = path
        # self.title = '导入'
    
    def case_type_check(self):
        """用例校验
        :return:
        """
        case_content = self.get_file_data('title')
        case_data = CaseData(case_content, self.path, self.import_type)
        # 解析x_mind数据
        topics = self.get_file_data()
        data = CaseData.get_case_data(case_data, topics)
        return data, '成功'
    
    def case_library_check(self):
        """用例库校验
        :return:
        """
        case_title = self.get_file_data('title')
        case_data = CaseData(case_title, self.path)
        title = '用例库:{}'.format(case_title)
        # 解析x_mind数据
        topics = self.get_file_data()
        data, msg = CaseData.get_case_data(case_data, topics)
        return data, msg, title
    
    # todo
    def case_check(self):
        """用例校验
        :return:
        """
        return None
    
    @lru_cache(maxsize=2)
    def get_file_data(self, title=None):
        """获取x_mind数据
        :param title: 一级标题
        :return:
        """
        try:
            workbook = xmind.load(self.path)
            # xmind.save(workbook)
            data = workbook.getData()
            topic = data[0].get("topic")
            # 获取xmind 一级标题
            if title:
                # xmind版本问题
                if topic.get('title').find('Warning') != -1:
                    raise Exception("xmind版本不支持zen,请下载xmind8版本")
                return topic.get('title')
            topics = topic.get('topics')
            return topics
        except IOError as error:
            current_app.logger.error(str(error))
            return None
